package com.ng.common.result;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 通用响应信息主体
 * @param <T>
 *
 * @author Ng
 * @date 2024/03/07
 */
@SuppressWarnings("unchecked")  // 去除类型强制转换警告
public class R<T> implements Serializable {

    private Integer code;
    private String msg;
    private T data;

    public static final Integer ERROR = 400;
    public static final Integer SUCCESS = 200;

    public int getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> R<T> success() {
        return result(SUCCESS, "操作成功", null);
    }

    public static <T> R<T> success(T data) {
        return result(SUCCESS, "操作成功", data);
    }

    public static <T> R<T> success(String msg, T data) {
        return result(SUCCESS, msg, data);
    }

    public static <T> R<T> error() {
        return result(ERROR, "操作失败", null);
    }

    public static <T> R<T> error(String msg) {
        return result(ERROR, msg, null);
    }

    public static <T> R<T> error(T data) {
        return result(ERROR, "操作失败", data);
    }

    public static <T> R<T> error(String msg, T data) {
        return result(ERROR, msg, data);
    }

    public static <T> R<T> error(Integer code, String msg) {
        return result(code, msg, null);
    }

    private static <T> R<T> result(Integer code, String msg, T data) {

        R<T> result = new R<>();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data != null ? data : (T) new HashMap<>());
        return result;
    }
}
